import React, {useEffect, useState} from 'react';
import {Badge, Button, Drawer, Form, Input, message, Modal, Select, Space, Statistic, Table, Tag} from "antd";
import {PAGE_INIT, PageInfo} from "../type";
import services from "../services";
import {
    CheckCircleOutlined, EditTwoTone,
    FileOutlined,
    HistoryOutlined,
    NumberOutlined,
    PlusCircleOutlined,
    SearchOutlined, TrophyTwoTone
} from '@ant-design/icons';
import ScoreAnalysis from "../analysis/ScoreAnalysis";
import EasyTypeAnalysis from "../analysis/EasyTypeAnalysis";


const {Option} = Select;

const assessmentMethodEnum = [
    {id: 0, option: "闭卷考试", color: "red"},
    {id: 1, option: "开卷考试", color: "orange"},
    {id: 2, option: "实验/上机考试", color: "green"},
    {id: 3, option: "课程论文/报告", color: "blue"},
    {id: 4, option: "课堂表现", color: "purple"},
];

const Course: React.FC = () => {
    const [courseList, setCourseList] = useState([]);
    const [assessmentMethod, setAssessmentMethod] = useState(); // 考核方式
    const [pageInfo, setPageInfo] = useState<PageInfo>(PAGE_INIT);
    const [loading, setLoading] = useState(false); // 加载状态
    const [keyWord, setKeyWord] = useState(''); // 搜索关键字
    const [editCourseVisible, setEditCourseVisible] = useState(false); // 编辑课程弹窗状态
    const [addCourseVisible, setAddCourseVisible] = useState(false); // 添加课程弹窗状态
    const [editCourseForm] = Form.useForm(); // 修改课程的信息
    const [addForm] = Form.useForm();
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [drawerData, setDrawerData] = useState();


    useEffect(() => {
        services.queryCourse({keyWord: '', pageNum: PAGE_INIT.pageNum, pageSize: PAGE_INIT.pageSize}).then(data => {
            setPageInfo({...pageInfo, pageNum: data.pageNum, total: data.total});
            setCourseList(data?.list || [])
        })
    }, []);


    const OnAddCourse = async () => {
        try {
            await addForm.validateFields();
            const values = await addForm.getFieldsValue();
            services.addCourse(values).then(data => {
                if (data === true) {
                    message.success("添加课程成功")
                    OnQueryCourse();
                    addForm.resetFields();
                    setAddCourseVisible(false);
                }
            })
        } catch (error) {
            return;
        }
    };


    function OnQueryCourse() {
        setCourseList([])
        setLoading(true)
        services.queryCourse({
            keyWord: keyWord,
            assessmentMethod: assessmentMethod,
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize
        }).then(data => {
            setPageInfo({...pageInfo, pageNum: data.pageNum, total: data.total});
            setCourseList(data?.list || [])
        }).finally(() => {
            setLoading(false)
        });
    }

    const headers = [
        {
            width: 20,
            render: (text: any, record: any) => {
                return <div>
                    <NumberOutlined/>
                </div>
            }
        },
        {
            title: '编号',
            dataIndex: 'courseNo',
            key: 'courseNo',
            // width: 200,
        },
        {
            title: '课程名称',
            dataIndex: 'name',
            key: 'name',
            // width: 200,
        },
        {
            title: '考核方式',
            dataIndex: 'assessmentMethod',
            key: 'assessmentMethod',
            width: 200,
            render: (text: any, record: any) => {
                let foundOption = assessmentMethodEnum.find(item => item.id === record.assessmentMethod);
                const option = foundOption ? foundOption : {id: -1, option: '未知', color: 'gray'};
                return (
                    <Tag color={option.color}>{option.option}</Tag>
                );
            }
        },
        {
            title: '考核内容',
            dataIndex: 'assessmentContent',
            key: 'assessmentContent',
            // width: 400,
            ellipsis: true,
            render: (text: any, record: any) =>
                <span style={{
                    display: '-webkit-box',
                    WebkitBoxOrient: 'vertical',
                    WebkitLineClamp: 2,
                    overflow: 'hidden'
                }}>{text}</span>,
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            // width: 200,
            ellipsis: false
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 200,
        },
        {
            title: '最后修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            width: 200,
        },
        {
            title: '操作',
            width: 300,

            render: (text: any, record: any) => {
                return <Space>
                    <Button
                        icon={<SearchOutlined/>}
                        onClick={() => {
                            let foundOption = assessmentMethodEnum.find(item => item.id === record.assessmentMethod);
                            const option = foundOption ? foundOption : {id: -1, option: '未知', color: 'gray'};

                            Modal.confirm({
                                title: "查看课程详情【" + record.name + "】",
                                content: (
                                    <Form>
                                        <Form.Item label="课程编号">
                                            <Input readOnly value={record.courseNo}/>
                                        </Form.Item>
                                        <Form.Item label="课程名称">
                                            <Input readOnly value={record.name}/>
                                        </Form.Item>
                                        <Form.Item label="考核方式">
                                            <Tag color={option.color}>{option.option}</Tag>
                                        </Form.Item>
                                        <Form.Item label="考核内容">
                                            <Input.TextArea
                                                autoSize={{minRows: 3, maxRows: 8}}
                                                readOnly
                                                value={record.assessmentContent}/>
                                        </Form.Item>
                                        <Form.Item label=" 备注 ">
                                            <Input.TextArea
                                                autoSize={{minRows: 2, maxRows: 5}}
                                                readOnly
                                                value={record.remark}/>
                                        </Form.Item>
                                        <Form.Item label="创建时间">
                                            <Tag color='gray'>{record.createTime}</Tag>
                                        </Form.Item>
                                        <Form.Item label="最后修改时间">
                                            <Tag color="green">{record.updateTime}</Tag>
                                        </Form.Item>
                                    </Form>
                                ),
                                okText: "确定",
                                cancelText: "取消",
                                width: 800,
                            })
                        }
                        }
                    >查看详情</Button>
                    <Button type="link" onClick={() => {
                        setEditCourseVisible(true);
                        console.log(record)
                        editCourseForm.setFieldsValue(record);
                    }
                    }>修改</Button>
                    <Button
                        danger
                        type="text"
                        onClick={() => {
                            Modal.confirm({
                                title: "删除课程",
                                content: "确定删除课程【" + record.name + "】吗？该课程下的作业和学习记录都会被删除，且删除后无法恢复！",
                                okText: "确定",
                                cancelText: "取消",
                                onOk: () => {
                                    services.deleteCourse({courseId: record.id})
                                        .then((data) => {
                                            message.success(data ? "删除成功" : "删除失败");
                                            OnQueryCourse();
                                        })
                                },
                            })
                        }
                        }
                    >删除</Button>
                    <Button
                        type='primary'
                        onClick={() => {
                            setDrawerVisible(true);
                            setDrawerData(record);
                        }}
                    >情况分析</Button>
                </Space>
                    ;
            }
        },
    ]


    const OnEditCourse = async () => {
        try {
            await editCourseForm.validateFields();
            const values = await editCourseForm.getFieldsValue();
            services.updateCourse(values).then(data => {
                if (data === true) {
                    message.success("修改成功")
                    OnQueryCourse();
                    editCourseForm.resetFields();
                    setEditCourseVisible(false);
                }
            })
        } catch (error) {
            return;
        }
    }

    return <div>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
            <h1>我的课程</h1>
            <Button
                className="custom-green-button"
                style={{margin: '20px 0 20px 30px'}}
                onClick={() => {
                    setAddCourseVisible(true);
                }}
                icon={<PlusCircleOutlined/>}
            >
                新增我的课程 </Button>
        </div>
        <div style={{
            marginBottom: '50px',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
        }}>
            <Space size={30}>
                <Input
                    placeholder="请输入课程名称进行搜索"
                    value={keyWord}
                    allowClear
                    onChange={(event) => {
                        setKeyWord(event.target.value);
                    }}
                    style={{width: '300px'}} // 设置样式
                />
                <Select
                    style={{width: '200px'}}
                    allowClear={true}
                    placeholder='请选择考核方式'
                    value={assessmentMethod}
                    onChange={setAssessmentMethod}>
                    {assessmentMethodEnum.map((data) => <Option key={data.id} value={data.id}>
                            {data.option}
                        </Option>
                    )
                    }
                </Select>
                <Button type="primary" onClick={OnQueryCourse}>查询</Button>
            </Space>
        </div>
        <div style={{width: '100%', display: 'flex'}}>
            <Table
                columns={headers}
                dataSource={courseList}
                loading={loading}
                pagination={{
                    current: pageInfo.pageNum,
                    pageSize: pageInfo.pageSize,
                    total: pageInfo.total,
                }}
                onChange={(pagination, filters, sorter) => {
                    setPageInfo({
                        ...pageInfo,
                        pageNum: pagination.current || 1,
                        pageSize: pagination.pageSize || 15
                    });
                }}/>
        </div>


        <Modal
            visible={addCourseVisible}
            title={"新增我的课程"}
            onCancel={() => {
                setAddCourseVisible(false);
                addForm.resetFields();
            }}
            cancelText={"取消"}
            okText={"确定添加"}
            onOk={() => {
                OnAddCourse();
            }
            }
        >
            <Form form={addForm}>
                <Form.Item label="课程编号" name="courseNo" rules={[{required: true, message: '请输入课程编号'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input/>
                </Form.Item>
                <Form.Item label="课程名称" name="name" rules={[{required: true, message: '请输入课程名称'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input/>
                </Form.Item>
                <Form.Item label="考核方式" name="assessmentMethod"
                           rules={[{required: true, message: '请输入考核方式'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Select
                        style={{width: '200px'}}
                        allowClear={true}
                        placeholder='请选择考核方式'
                        onChange={(value) => {
                            addForm.setFieldsValue({assessmentMethod: value});
                        }
                        }
                    >
                        {assessmentMethodEnum.map((data) => <Option key={data.id} value={data.id}>
                                {data.option}
                            </Option>
                        )
                        }
                    </Select>
                </Form.Item>
                <Form.Item label="考核内容" name="assessmentContent"
                           rules={[{required: true, message: '请输入考核内容'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input.TextArea autoSize={{minRows: 3, maxRows: 8}}/>
                </Form.Item>
                <Form.Item label="备注" name="remark" labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input.TextArea autoSize={{minRows: 3, maxRows: 8}}/>
                </Form.Item>
            </Form>
        </Modal>

        <Modal
            visible={editCourseVisible}
            title={"编辑课程信息【" + editCourseForm.getFieldValue("name") + "】"}
            onCancel={() => {
                setEditCourseVisible(false);
                addForm.resetFields();
            }}
            cancelText={"取消"}
            okText={"确定修改"}
            onOk={() => {
                OnEditCourse();
            }
            }
        >
            <Form form={editCourseForm}>
                <Form.Item label={'id'} name="id" className='hidden-field'>
                    <Input placeholder="id"/>
                </Form.Item>
                <Form.Item label="课程编号" name="courseNo" rules={[{required: true, message: '请输入课程编号'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input/>
                </Form.Item>
                <Form.Item label="课程名称" name="name" rules={[{required: true, message: '请输入课程名称'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input/>
                </Form.Item>
                <Form.Item label="考核方式" name="assessmentMethod"
                           rules={[{required: true, message: '请输入考核方式'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Select
                        style={{width: '200px'}}
                        allowClear={true}
                        placeholder='请选择考核方式'
                        onChange={(value) => {
                            editCourseForm.setFieldsValue({assessmentMethod: value});
                        }
                        }
                    >
                        {assessmentMethodEnum.map((data) => <Option key={data.id} value={data.id}>
                                {data.option}
                            </Option>
                        )
                        }
                    </Select>
                </Form.Item>
                <Form.Item label="考核内容" name="assessmentContent"
                           rules={[{required: true, message: '请输入考核内容'}]}
                           labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input.TextArea autoSize={{minRows: 3, maxRows: 8}}/>
                </Form.Item>
                <Form.Item label="备注" name="remark" labelCol={{span: 6}} wrapperCol={{span: 18}}>
                    <Input.TextArea autoSize={{minRows: 3, maxRows: 8}}/>
                </Form.Item>
            </Form>
        </Modal>


        <Drawer
            // @ts-ignore
            // @ts-ignore
            title={"课程【" + drawerData?.name + "】" + "的学习记录情况分析"}
            placement="right"
            closable={false}
            onClose={() => {
                setDrawerVisible(false);
            }}
            visible={drawerVisible}
            extra={
                <Space>
                    <Button onClick={() => {
                        setDrawerVisible(false);
                    }
                    } type='primary'>关闭</Button>
                </Space>
            }
            width="66.6667%"
        >

                <div style={{display: 'flex', justifyContent: 'center'}}>
                    <Statistic title="作业总数"
                        // @ts-ignore
                               value={drawerData?.totalWorkNumber} style={{margin: '0 160px'}}
                               prefix={<FileOutlined/>}/>
                    <Statistic title="学习记录总数"
                        // @ts-ignore
                               value={drawerData?.totalLearnRecordNumber} style={{margin: '0 160px'}}
                               prefix={<TrophyTwoTone/>}/>
                </div>

            <div style={{
                backgroundColor: '#d9d9d9',
                borderRadius: '10px',
                transform: 'scale(0.92)'
            }}>
                <h2>（1）分数统计</h2>
                <ScoreAnalysis
                    // @ts-ignore
                    scores={drawerData?.learnRecordForWorkResp}
                />
            </div>

            <div style={{
                backgroundColor: '#f9cb9c',
                borderRadius: '10px',
                transform: 'scale(0.92)'
            }}>
                <h2>（2）难易程度统计</h2>
                <EasyTypeAnalysis
                    // @ts-ignore
                    learnRecords={drawerData?.learnRecordForWorkResp}
                />
            </div>
        </Drawer>
    </div>;
};

export default Course;